<template>
  <uni-popup ref="addPopup" type="center" border-radius="20px">
    <view class="popup">
      <view class="head">
        <text>添加设备</text>
        <uni-icons type="clear" size="25" color="#aaa" style="opacity: 0.5" @click="closeAddComputer"></uni-icons>
      </view>
      <view class="body">
        <uni-forms ref="addComputerForm" :modelValue="addComputerInfo" :rules="addComputerInfoRules" label-position="left">
          <uni-forms-item label="主机名称" name="name">
            <uni-easyinput type="text" :trim="true" v-model="addComputerInfo.name" placeholder="请输入主机名称(非必填)" />
          </uni-forms-item>
          <uni-forms-item label="ip地址/域名" name="ip" required>
            <uni-easyinput type="text" :trim="true" v-model="addComputerInfo.ip" placeholder="请输入主机ip或者域名" />
          </uni-forms-item>
          <uni-forms-item label="端口号" name="port">
            <uni-easyinput type="text" :trim="true" v-model="addComputerInfo.port" placeholder="请输入端口号(默认8000)" />
          </uni-forms-item>
          <uni-forms-item label="密钥" name="key" required>
            <uni-easyinput type="text" :trim="true" v-model="addComputerInfo.key" placeholder="请输入密钥" />
          </uni-forms-item>
        </uni-forms>
        <button class="base-button" @click="addComputerEvent">{{ props.computerInfo.ip ? "修改" : "添加" }}设备信息</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup name="computerForm">
import { getComputerInfo } from "@/api/control.js";
import { ref } from "vue";
import { storeToRefs } from "pinia";
import useComputerStore from "@/store/modules/computer.js";
import _ from "lodash";
import { isAuthPass } from "../../utils/authentication";

const computerStore = useComputerStore();
const { computerList } = storeToRefs(computerStore);

const props = defineProps({
  computerInfo: {
    type: Object,
    default: {
      name: "",
      ip: "",
      port: "",
      key: "",
    },
  },
});
// 添加设备窗口实例
const addPopup = ref();
// 打开添加设备窗口
const openAddComputer = () => {
  if (props.computerInfo) {
    Object.assign(addComputerInfo.value, _.cloneDeep(props.computerInfo));
  }
  addPopup.value.open("center");
};

// 关闭添加设备窗口
const closeAddComputer = () => {
  addPopup.value.close();
};

//添加设备表单校验规则
const addComputerInfoRules = {
  name: {
    // name 字段的校验规则
    rules: [],
    validateTrigger: "submit",
  },
  ip: {
    rules: [
      {
        required: true,
        errorMessage: "ip/域名不可以为空",
      },
    ],
    validateTrigger: "submit",
  },
  port: {
    rules: [
      {
        pattern: /^\d{1,5}$/g,
        errorMessage: "端口号格式不正确",
      },
    ],
    validateTrigger: "submit",
  },
  key: {
    rules: [
      {
        required: true,
        errorMessage: "密钥不可以为空",
      },
    ],
    validateTrigger: "submit",
  },
};

// 添加设备表单
const addComputerInfo = ref({
  name: "",
  ip: "",
  port: "",
});

// 表单实例
const addComputerForm = ref();

// 添加设备事件
const addComputerEvent = async () => {
  if (isAuthPass()) return;
  let validateData = await addComputerForm.value.validate();
  // let
  if (!props.computerInfo.ip) {
    if (computerList.value.some((item) => item.ip === addComputerInfo.value.ip && item.port === addComputerInfo.value.port)) {
      uni.showToast({
        title: "设备已存在",
        icon: "none",
      });
    } else {
      uni.showLoading({
        title: "查询中",
      });
      // try {
      let res = await getComputerInfo(addComputerInfo.value);
      if (res.code === 200) {
        addComputerInfo.value.status = "在线";
      } else {
        addComputerInfo.value.status = "离线";
      }
      computerList.value.push(addComputerInfo.value);
      computerStore.updateComputerList(_.cloneDeep(computerList.value));
      closeAddComputer();
      uni.hideLoading();
      uni.showToast({
        title: "添加成功",
        icon: "success",
      });
    }
  } else {
    // 当前修改的元素下标
    let index = computerList.value.findIndex((item) => item.ip === props.computerInfo.ip && item.port === props.computerInfo.port);

    let isRepetition = false;
    for (let i = 0; i < computerList.value.length; i++) {
      if (i === index) {
        continue;
      } else {
        if (computerList.value[i].ip === addComputerInfo.value.ip && computerList.value[i].port === addComputerInfo.value.port) {
          isRepetition = true;
          break;
        }
      }
    }
    if (isRepetition) {
      uni.showToast({
        title: "设备已存在",
        icon: "none",
      });
      closeAddComputer();
    } else {
      uni.showLoading({
        title: "查询中",
      });
      let res = await getComputerInfo(addComputerInfo.value);
      if (res.code === 200) {
        addComputerInfo.value.status = "在线";
      } else {
        addComputerInfo.value.status = "离线";
      }
      computerList.value[index] = addComputerInfo.value;

      computerStore.updateComputerList(_.cloneDeep(computerList.value));
      closeAddComputer();
      uni.hideLoading();
      uni.redirectTo({
        url: `/pages/detail/index?ip=${addComputerInfo.value.ip}&port=${addComputerInfo.value.port}`,
      });
      uni.showToast({
        title: "修改成功",
        icon: "success",
      });
    }
  }
};

defineExpose({ openAddComputer });
</script>

<style lang="scss" scoped>
.popup {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
  box-sizing: border-box;
  padding: 20rpx;
  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;

    text {
      font-size: 35rpx;
      font-weight: bold;
      color: #333;
    }
  }
  .body {
    margin-top: 20px;
  }
}
</style>
